// $codepro.audit.disable
/* Copyright (c) 2011 Team A CS2340. All rights reserved.*/

package edu.gatech.teama.doctorsoffice.client.view;

import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;



import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.RowSpec;

import edu.gatech.teama.doctorsoffice.client.presenter.ServerConnection;
import edu.gatech.teama.doctorsoffice.client.presenter.UserLookupPresenter;
import edu.gatech.teama.doctorsoffice.model.SystemAdmin;
import edu.gatech.teama.doctorsoffice.model.User;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
 * myPresenter
 * @author unknown
 * @version 1.0
 */
public class UserLookupPanel extends JPanel {
	/**
	 * myPresenter
	 */
	private UserLookupPresenter myPresenter;
	/**
	 * table
	 */
	private JScrollPane tableScrollPane;

	private JTable table;
	/**
	 * search field
	 */
	private JTextField searchField;

	private JLabel lblName;

	private JLabel lblAddress_1;

	private JLabel lblAddress_2;

	private JLabel lblPhone;

	private JLabel lblEmail;

	/**
	 * Create the panel.
	 */
	public UserLookupPanel() { // $codepro.audit.disable com.instantiations.assist.eclipse.analysis.audit.rule.effectivejava.constructorsOnlyInvokeFinalMethods
		final ServerConnection sc = ServerConnection.getInstance();

		JButton btnAddNewUser = new JButton("Add New User");
		btnAddNewUser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				myPresenter.addNewUser();
				myPresenter.fireUserListChanged();
				((AbstractTableModel) table.getModel()).fireTableStructureChanged();
			}
		});
		setLayout(new MigLayout("", "[grow][70px][5px][83px][5px][grow]", "[23px][27px][11px][23px][3px][14px][3px][14px][3px][14px][3px][14px][3px][14px][33px][grow]"));
		add(btnAddNewUser, "cell 0 0,alignx right,aligny top");



		table = new JTable();
		/*table.setModel(new DefaultTableModel(
			new Object[][] {
				{null, null},
			},
			new String[] {
				"Name", "Address"
			}
		) {
			Class[] columnTypes = new Class[] {
				String.class, String.class
			};
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
			boolean[] columnEditables = new boolean[] {
				false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});*/
		table.setAutoCreateColumnsFromModel(true);
		table.setModel(new AbstractTableModel() {
			/**
			 * column names
			 */
			private String[] columnNames = new String[] {
					"Name", "Username"
			};

			@Override
			public String getColumnName(int col) {
				return columnNames[col].toString();
			}

			@Override
			public Object getValueAt(int rowIndex, int columnIndex) {
				// TODO Auto-generated method stub
				User userAtRow = myPresenter.getUserAtTableRow(rowIndex);
				if (columnNames[columnIndex].equals("Name")) {
					return userAtRow.getFirstName() + " " + userAtRow.getLastName();
				}
				if (columnNames[columnIndex].equals("Username")) {
					return userAtRow.getUsername();
				}
				return null;
			}

			@Override
			public int getRowCount() {
				// TODO Auto-generated method stub
				return myPresenter.getNumberOfVisibleUsers();
			}

			@Override
			public int getColumnCount() {
				// TODO Auto-generated method stub
				return columnNames.length;
			}
		});
		table.setFillsViewportHeight(true);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);



		tableScrollPane = new JScrollPane(table);
		add(tableScrollPane, "cell 0 1 1 15,grow");

		JLabel lblSearch = new JLabel("Search:");
		add(lblSearch, "cell 1 1,alignx right,aligny bottom");

		searchField = new JTextField();
		searchField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				((AbstractTableModel) table.getModel()).fireTableStructureChanged();
				myPresenter.lookupPatient(searchField.getText());
				((AbstractTableModel) table.getModel()).fireTableStructureChanged();
			}
		});
		add(searchField, "cell 3 1 3 1,growx,aligny bottom");
		searchField.setColumns(10);

		JLabel lblSelectedUser = new JLabel("Selected User:");
		add(lblSelectedUser, "cell 1 3,alignx right,aligny center");

		JButton btnOpen = new JButton("Open");
		add(btnOpen, "cell 3 3,alignx left,aligny top");

		JLabel _lblName = new JLabel("Name:");
		add(_lblName, "cell 3 5,alignx left,aligny top");

		lblName = new JLabel("name");
		add(lblName, "cell 5 5,alignx left,aligny top");

		JLabel _lblAddress = new JLabel("Address:");
		add(_lblAddress, "cell 3 7,alignx left,aligny top");

		lblAddress_1 = new JLabel("address 1");
		add(lblAddress_1, "cell 5 7,alignx left,aligny top");

		lblAddress_2 = new JLabel("address 2");
		add(lblAddress_2, "cell 5 9,alignx left,aligny top");

		JLabel _lblPhone = new JLabel("Phone:");
		add(_lblPhone, "cell 3 11,alignx left,aligny top");

		lblPhone = new JLabel("phone");
		add(lblPhone, "cell 5 11,alignx left,aligny top");

		JLabel _lblEmail = new JLabel("E-mail:");
		add(_lblEmail, "cell 3 13,alignx left,aligny top");

		lblEmail = new JLabel("email");
		add(lblEmail, "cell 5 13,alignx left,aligny top");

		JPanel panel = new JPanel();
		add(panel, "cell 1 15 5 1,grow");
		panel.setLayout(new MigLayout("", "[63px][95px][109px]", "[23px]"));

		JButton btnDelete = new JButton("Delete");
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object[] options = {"Yes",
						"No",};
				int n = JOptionPane.showConfirmDialog(MainWindow.getFrame(),
						"Are you sure you want to delete?", "Delete User", JOptionPane.YES_NO_OPTION);

				if (n == JOptionPane.YES_OPTION) {
					User deleting = myPresenter.userAtIndex(table.getSelectedRow());
					if (deleting != null) {
						sc.deleteUser(deleting.getUsername());
						myPresenter.fireUserListChanged();
						((AbstractTableModel) table.getModel()).fireTableStructureChanged();
					}
				}
			}
		});
		panel.add(btnDelete, "cell 0 0,alignx left,aligny top");

		final JButton btnLockAccount = new JButton("Lock Account");
		JButton btnResetPassword = new JButton("Reset Password");

		btnLockAccount.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				User u = myPresenter.userSelected(table.getSelectedRow());
				if (btnLockAccount.getText().equalsIgnoreCase("Lock Account")) {
					u.setFailedLoginAttempts(10);
				} else if (btnLockAccount.getText().equalsIgnoreCase("Unlock Account")) {
					u.setFailedLoginAttempts(0);
				}
				sc.updateUser(u);
				myPresenter.fireUserListChanged();
				int oldSelection = table.getSelectedRow();
				table.clearSelection();
				table.setRowSelectionInterval(oldSelection, oldSelection);
			}
		});

		btnResetPassword.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				User u = myPresenter.userSelected(table.getSelectedRow());
				String newPass = JOptionPane.showInputDialog("New password:");
				sc.changePassword(u, newPass);
			}
		});

		if (sc.getLoggedInUser() instanceof SystemAdmin) {
			panel.add(btnLockAccount, "cell 1 0,alignx left,aligny top");
			panel.add(btnResetPassword, "cell 2 0,alignx left,aligny top");
		}

		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				// TODO Auto-generated method stub
				if (table.getSelectedRow() >=0) {
					User u = myPresenter.userSelected(table.getSelectedRow());
					if (u.getFailedLoginAttempts() >= 3) {
						btnLockAccount.setText("Unlock Account");
					} else {
						btnLockAccount.setText("Lock Account");
					}
				}
			}
		});

		myPresenter = new UserLookupPresenter(this);

	}

	public void setSelectedUserInfo(String name, String address_1, String address_2, String phone, String email) {
		lblName.setText("");
		lblAddress_1.setText("");
		lblAddress_2.setText("");
		lblPhone.setText("");
		lblEmail.setText("");

		lblName.setText(name);
		lblAddress_1.setText(address_1);
		lblAddress_2.setText(address_2);
		lblPhone.setText(phone);
		lblEmail.setText(email);
	}

}
